/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package backupit.core.io;

import backupit.core.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.TreeMap;

/**
 *
 * @author dbotelho
 */
public class FileInfoSetWriter {

    private String root;
    private TreeMap<File, File> dirs;

    public FileInfoSetWriter(String root) {
        this.root = root;
        this.dirs = new TreeMap<File, File>();
    }

    public long write(FileInfoSet set) throws IOException {
        long bytes = 0;
        for (FileInfo file : set) {
            bytes += write(file);
        }

        //update directories lastModified
        for (File source : dirs.keySet()) {
            dirs.get(source).setLastModified(source.lastModified());
        }


        return bytes;
    }

    protected long write(FileInfo fileInfo) throws IOException {
        File source = new File(fileInfo.getAbsolutePath());
        File dest = new File(this.root + fileInfo.getRelativePath());

        if (source.isDirectory()) {
            dirs.put(source, dest);
        }
        return write(source, dest);
    }

    protected long write(File from, File to) throws IOException {
        long numWritten = 0;

        if (from.isDirectory()) {
            System.out.println(to.getPath() + " ");
            to.mkdir();
        } else {

            OutputStream out = null;
            InputStream in = null;

            try {
                out = new BufferedOutputStream(
                        new FileOutputStream(to));
                in = new FileInputStream(from);
                byte[] buffer = new byte[1024];
                int numRead;

                while ((numRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, numRead);
                    numWritten += numRead;
                }
            } catch (IOException exception) {
                exception.printStackTrace();
                throw new IOException(exception.getMessage());
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    if (out != null) {
                        out.close();
                    }

                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            to.setLastModified(from.lastModified());
            to = null;
            from = null;
        }

        return numWritten;
    }
}
